package com.example.applications

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.myapplication.DetailFragment
import com.example.myapplication.ListFragment

class MainActivity : AppCompatActivity(), ListFragment.OnItemSelectedListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 添加ListFragment作为启动页面
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.main, com.example.myapplication.ListFragment())
                .commit()
        }
    }

    override fun onItemSelected(itemId: Int) {
        // 创建详情Fragment实例
        val detailFragment = DetailFragment()

        // 执行Fragment事务，替换当前容器中的Fragment，并添加到返回栈以便返回列表页
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, detailFragment)
            .addToBackStack(null) // 添加到返回栈，参数为null表示不使用名称标识
            .commit()
    }
}